package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.astrob.activitys.AppContext;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.FileUtils;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.manager.IECenter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.PageScroller;

public class DaoruActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "DaoruActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, DaoruActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daoru_activity);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private TextView tv_daoru;
    private ListView lv_all;
    private Button bt_selectall;
    private Button bt_share;
    private Button bt_daoru;

    @Override
    public void initView() {//必须调用
        tv_daoru = (TextView) findViewById(R.id.tv_daoru);
        tv_daoru.setTypeface(AppContext.getInstances().getIconfont());
        bt_daoru = (Button) findViewById(R.id.bt_daoru);
        bt_selectall = (Button) findViewById(R.id.bt_selectall);
        bt_share = (Button) findViewById(R.id.bt_share);
        lv_all = (ListView) findViewById(R.id.lv_all);
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initData() {//必须调用
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetAlldata();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList();
                    }
                });
            }
        });
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须调用
        tv_daoru.setOnClickListener(this);
        bt_daoru.setOnClickListener(this);

        lv_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                boolean isSelected = hashMap.get(position);
                hashMap.put(position, !isSelected);
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }

                int selectednum = 0;
                for (int i = 0; i < filelist.size(); i++) {
                    if (hashMap.get(i)) {
                        selectednum++;
                    }
                }

                if (selectednum == filelist.size()) {
                    _isSelectedAll = true;
                    bt_selectall.setText(getString(R.string.selectallno));
                } else {
                    _isSelectedAll = false;
                    bt_selectall.setText(getString(R.string.selectall));
                }

            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_all).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>
    }
    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    //SD卡 -- /mnt/sdcard2/
    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private void resetAlldata() {
        filelist = new ArrayList<Entry<Integer, String>>();
        //
        if (SysUtils.getInstance().is240x320) {
            seachFile(Environment.getExternalStorageDirectory() + "/GPX");
            seachFile(Environment.getExternalStorageDirectory() + "/KML");
        } else {
            String EXDIR0 = Start.RUNDIR + "/HCMap_EX/";
//        String EXDIR1 = Utils.getSDPath() + "/HCMap_EX/";
//        String paths[] = {EXDIR0, EXDIR1};
            String paths[] = {EXDIR0};
            seachFile(EXDIR0);
        }


        //
        boolean isSelected = false;
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        for (int i = 0; i < filelist.size(); i++) {
            hashMap.put(i, isSelected);
        }
    }

    int _num = 0;

    private void seachFile(String path) {
        File fRoot = new File(path);
        File[] files = fRoot.listFiles();
        if (files == null)
            return;

        for (int j = 0; j < files.length; j++) {
            String fName = files[j].getName();
            if (files[j].isDirectory()) {
                seachFile(files[j].getPath());
            } else {
                if (fName.contains(".gpx") || fName.contains(".KML") || fName.contains(".kml") || fName.contains(".kmz")) {
                    filelist.add(new Entry<Integer, String>(_num, files[j].getPath()));
                    _num++;
                }
            }
        }
    }

    private List<Entry<Integer, String>> filelist;
    private HashMap<Integer, Boolean> hashMap;

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     */
    private void setList() {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_all.setAdapter(adapter);
        }
        adapter.refresh(filelist);

        if (filelist.size() < 1) {
            showShortToast(getString(R.string.daoru_toast_0));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_daoru:
            case R.id.bt_daoru:
                onDaoru();
                break;
            default:
                break;
        }
    }

    boolean _isSelectedAll = false;//true-已经全选

    public void onSelectAll(View v) {

        if (_isSelectedAll) {
            selectAll(false);
            _isSelectedAll = false;
            bt_selectall.setText(getString(R.string.selectall));
        } else {
            selectAll(true);
            _isSelectedAll = true;
            bt_selectall.setText(getString(R.string.selectallno));
        }


    }

    public void onShare(View v) {
        if (filelist.size() < 1) {
            return;
        }

        ArrayList<Uri> files = new ArrayList<Uri>();
        for (int i = 0; i < filelist.size(); i++) {
            if (hashMap.get(i)) {
                String filePath = filelist.get(i).getValue();
                files.add(Uri.fromFile(new File(filePath)));
            }
        }

        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);//发送多个文件
        intent.setType("*/*");//多个文件格式
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,files);//Intent.EXTRA_STREAM同于传输文件流
        startActivity(intent);
    }

    public void onSelectAllNO(View v) {
        selectAll(false);
    }

    public void selectAll(boolean isSelected) {
        for (int i = 0; i < filelist.size(); i++) {
            hashMap.put(i, isSelected);
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }
    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public void onDaoru() {
        if (filelist.size() < 1) {
            showShortToast(getString(R.string.daoru_toast_1));
            return;
        }

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                doDaoru();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        finishDaoru();
                    }
                });
            }
        });

    }
    boolean _daoruOK = false;

    private boolean doDaoru() {
        _daoruOK = false;
        ArrayList<String> daoru = new ArrayList<String>();
        for (int i = 0; i < filelist.size(); i++) {
            boolean success = false;
            if (hashMap.get(i)) {
                String filePath = filelist.get(i).getValue();
                daoru.add(filePath);
                if (filePath.contains(".gpx")) {
                    success = IECenter.getInstance().importGPX(filePath);
                } else if (filePath.contains(".KML") || filePath.contains(".kml")) {
                    success = IECenter.getInstance().importKML(filePath);
                } else if (filePath.contains(".kmz") || filePath.contains(".KMZ")) {
                    success = IECenter.getInstance().importKMZ(filePath);
                }
            }
            if (success) {
                _daoruOK = true;
            }
        }

        return _daoruOK;
    }

    private void finishDaoru() {
        if (_daoruOK) {
            showShortToast(getString(R.string.daoru_toast_2));
            setResult(RESULT_OK);
        } else {
            showShortToast("尚无记录!");
        }

        finish();
    }

    public void onDaoru2() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("gpx/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "选择gpx或KML的文件夹"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private final int FILE_SELECT_CODE = 30;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    String path = FileUtils.getPath(this, uri);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.daoru_view, parent, false);
            }

            TextView tv_name = BaseViewHolder.get(convertView, R.id.tv_name);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());

            final Entry<Integer, String> data = getItem(position);
            tv_name.setText(data.getValue());

            boolean isSelected = false;
            isSelected = hashMap.get(position);

            if (isSelected) {
                iv_check.setText(R.string.fonticon_xz);
            } else {
                iv_check.setText(R.string.fonticon_wxz);
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }
    }


}
